package com.ycsj.goldmedalnewconcept.common.activity;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;

import com.mob.MobSDK;
import com.ycsj.common.base.BaseActivity;
import com.ycsj.common.utils.StateBarUtil;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.common.util.TestTimeCountUtil;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import cn.sharesdk.sina.weibo.SinaWeibo;

/**
 * 通用-复习-词汇检测H5
 */
public class WordsTestActivity extends BaseActivity {

    private String rid;

    private WebView webView2;

    private MediaPlayer mPlayer;

    private String lESSON_ID;

    private MediaPlayer mediaPlayer = new MediaPlayer();

    private String classNum;

    private String classnum;

    private String logo;

    /**
     * 跳转到当前页面的方法
     *
     * @param context
     * @param lessonid
     */
    public static void goActivity(Context context, String lessonid, String classNum) {
        Intent it = new Intent(context, WordsTestActivity.class);
        it.putExtra("lESSON_ID", lessonid);
        it.putExtra("classnum", classNum);
        context.startActivity(it);
    }

    @Override
    protected int getContentLayout() {

        return R.layout.activity_fuxi;
    }

    @Override
    protected void init() {

        //沉浸状态栏
        StateBarUtil.customStateBar(this, getResources().getColor(R.color.h5title));

        //接收数据
        initIntent();

        //设置数据
        initView();
    }

    private void initIntent() {
        lESSON_ID = getIntent().getStringExtra("lESSON_ID");
        classNum = getIntent().getStringExtra("classnum");

        if ("0".equals(AccountUtils.getRole(this))) {
            classnum = AccountUtils.getClassNum(this);
        } else if ("2".equals(AccountUtils.getRole(this))) {
            classnum = classNum;
        }

        if (TextUtils.isEmpty(AccountUtils.getLogo(this))) {
            logo = "http://139.129.57.83:8080/Appandroid/applogo.png";
        } else {
            TextUtils.isEmpty(AccountUtils.getLogo(this));
        }
    }

    private void initView() {

        webView2 = findViewById(R.id.webView2);

        webView2.getSettings().setJavaScriptEnabled(true);
        webView2.getSettings().setBuiltInZoomControls(false);
        webView2.getSettings().setUseWideViewPort(true);
        webView2.getSettings().setRenderPriority(RenderPriority.HIGH);
        webView2.getSettings().setDatabaseEnabled(true);
        webView2.getSettings().setDomStorageEnabled(true);
        webView2.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView2.getSettings().setPluginState(PluginState.ON);

        webView2.loadData("", "text/html", null);
        webView2.getSettings().setPluginState(PluginState.ON);

        webView2.addJavascriptInterface(new WebAppInterface(this), "Android");

        long cur = System.currentTimeMillis();
        webView2.loadUrl(HttpAddress.DONEQUESTIONLIST + "?" + cur);

    }

    @Override
    protected void onPause() {
        super.onPause();

        //停止播放
        if (mediaPlayer != null) {

            mediaPlayer.pause();
        }

        //停止计时
        TestTimeCountUtil.stopTime(this, rid);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        String gradeid = lESSON_ID.substring(0, 4);
        //开始计时
        TestTimeCountUtil.startTime(this, "1", gradeid, lESSON_ID, new TestTimeCountUtil.onSuccessListener() {
            @Override
            public void onSuccess(String infoRid) {
                rid = infoRid;
            }
        });


    }


    @Override
    protected void onStop() {
        super.onStop();
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        webView2.setVisibility(View.GONE);
        webView2.removeAllViews();
        webView2.destroy();
        if (webView2 != null) {
            webView2 = null;
        }
        System.gc();
    }


    public class WebAppInterface {
        Context mContext;

        /**
         * Instantiate the interface and set the context
         */
        WebAppInterface(Context c) {
            mContext = c;
        }

        /**
         * Show a toast from the web page
         */
        @JavascriptInterface
        public void showToast(String toast) {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
                System.gc();
            }

            String uri;
            if ("http".equals(toast.substring(0, 4))) {
                uri = toast;
            } else {
                uri = "https://moregolden.com:8081/" + "html5/" + toast;
            }
            if (mediaPlayer == null) {
                mediaPlayer = MediaPlayer.create(WordsTestActivity.this,
                        Uri.parse(uri));
            }
            try {
                mediaPlayer.start();

                mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                    @Override
                    public void onCompletion(MediaPlayer mp) {
                        // TODO Auto-generated method stub
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        mediaPlayer = null;
                        System.gc();
                    }
                });

            } catch (Exception e) {
            }

        }

        // 传递参数
        @JavascriptInterface
        public String getParam() {

            String param = AccountUtils.getAccount(WordsTestActivity.this)
                    + ",1,"
                    + lESSON_ID
                    + ","
                    + AccountUtils.getRole(WordsTestActivity.this) + "," + AccountUtils.getSchoolId(WordsTestActivity.this) +
                    "," + AccountUtils.getTeacher(WordsTestActivity.this) + "," + classnum;
            Log.e("test", "param=" + param);
            return param;
        }

        // 展示成绩
        @JavascriptInterface
        public void showScore(String url, String exam_type) {

            ShowScoreActivity.goActivity(WordsTestActivity.this,
                    "https://www.moregolden.com:8081/JPXB/newJpjpage/" + url,
                    exam_type, lESSON_ID, classNum);

            finish();
            return;
        }

        // 关闭界面
        @JavascriptInterface
        public void finish() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    WordsTestActivity.this.finish();
                }
            });

            Log.e("test", "finish");
            return;
        }


        // 分享界面
        @JavascriptInterface
        public void share(final String total) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String[] StrArray = total.split("&");
                    clickShare(StrArray[3], StrArray[4]);
                    Log.e("test", "total=" + total);

                }
            });
            return;
        }

        // 播放正误音频
        @JavascriptInterface
        public void playertrueorfalse(int num) {
            Log.i("test", num + "num");

            if (mPlayer != null) {
                mPlayer.release();
                mPlayer = null;
            }
            if (num == 1) {

                mPlayer = MediaPlayer.create(WordsTestActivity.this, R.raw.rightmp3);
            } else if (num == 2) {

                mPlayer = MediaPlayer.create(WordsTestActivity.this, R.raw.errormp3);
            }
            mPlayer.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    if (mPlayer != null) {
                        mPlayer.release();
                        mPlayer = null;
                    }
                }
            });
            mPlayer.start();
            return;
        }
    }

    private void clickShare(final String totaltime, final String Score) {

        // TODO Auto-generated method stub
        MobSDK.init(WordsTestActivity.this, "12c24ea0b59b0",
                "aae63565fbd69b1acbfcdd0d5ac0b35c");
        OnekeyShare oks = new OnekeyShare();
        // 关闭sso授权
        oks.disableSSOWhenAuthorize();
        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {

            @Override
            public void onShare(Platform platform, ShareParams paramsToShare) {

                String url = HttpAddress.UPDATE_URL + "JPXB/sharePage/pages/JPXGN_JPXB/shareMark/shareMark.html?" +
                        "moduleType=0&userType=" + AccountUtils.getRole(WordsTestActivity.this) + "&"
                        + totaltime + "&" + Score + "&num="
                        + AccountUtils.getAccount(WordsTestActivity.this) + "&exam_type=1&normal=2";

                String title = AccountUtils.getName(WordsTestActivity.this)
                        + "在"
                        + "词汇检测"
                        + "环节花费了"
                        + totaltime.substring(5, totaltime.length())
                        + "秒获得" + Score.substring(5, Score.length()) + "分,为你点赞！";


                if (SinaWeibo.NAME.equals(platform.getName())) {
                    paramsToShare.setTitle("分享");

                    paramsToShare
                            .setTitleUrl(url);

                    paramsToShare.setTitle(AccountUtils.getName(WordsTestActivity.this)
                            + "在"
                            + "词汇检测"
                            + "环节花费了" + totaltime.substring(5, totaltime.length()) + "秒获得" + Score.substring(5, Score.length()) + "分,为你点赞！");
                    if (TextUtils.isEmpty(AccountUtils.getSchoolName(WordsTestActivity.this))) {
                        paramsToShare.setText("\n\r想展现你的实力吗?来这里比拼一下吧！");
                    } else {
                        paramsToShare.setText(AccountUtils.getSchoolName(WordsTestActivity.this));
                    }
                    paramsToShare
                            .setImageUrl(logo);
                    paramsToShare
                            .setUrl(url);
                    paramsToShare.setComment("");
                    paramsToShare.setSite(getString(R.string.app_name));
                    paramsToShare
                            .setSiteUrl(url);

                } else {
                    paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                    paramsToShare.setTitle("分享");
                    paramsToShare
                            .setTitleUrl(url);
                    paramsToShare.setTitle(AccountUtils.getName(WordsTestActivity.this)
                            + "在"
                            + "词汇检测"
                            + "环节花费了" + totaltime.substring(5, totaltime.length()) + "秒获得" + Score.substring(5, Score.length()) + "分,为你点赞！");
                    if (TextUtils.isEmpty(AccountUtils.getSchoolName(WordsTestActivity.this))) {
                        paramsToShare.setText("\n\r想展现你的实力吗?来这里比拼一下吧！");
                    } else {
                        paramsToShare.setText(AccountUtils.getSchoolName(WordsTestActivity.this));
                    }
                    paramsToShare
                            .setImageUrl(logo);
                    paramsToShare
                            .setUrl(url);
                    paramsToShare.setComment("");
                    paramsToShare.setSite(getString(R.string.app_name));
                    paramsToShare
                            .setSiteUrl(url);
                }
            }
        });

        // 启动分享GUI
        oks.show(this);
    }


    @Override
    public void finish() {
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();
        super.finish();
    }

}
